const { Service } = require("egg");

class CodeService extends Service {
    /**
     * 根据手机号，获取验证码记录
     * @param {string} mobile 用户手机号
     */
    async findByMobile(mobile) {
        let sql =
            "select mobile, code, create_time from code where mobile = ? limit 0, 1";
        let params = [mobile];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 根据手机号，删除对应的验证码记录
     * @param {string} mobile 手机号
     */
    async removeByMobile(mobile) {
        let sql = "delete from code where mobile = ?";
        let params = [mobile];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 将该手机验证码保存起来
     * @param {string} mobile 手机号码
     * @param {string} code 生成的验证码
     */
    async create(mobile, code) {
        let sql = "insert into code (mobile, code) values (?, ?)";
        let params = [mobile, code];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = CodeService;
